/**
 * Created by Myron on 2015/8/15.
 */
var async = require('async');
var config = require('../config.js');
var cartM = require('../models/cart.js');
var serviceM = require('../models/service.js');
var Order = require('../controllers/order.js');
var orderM = require('../models/order');
var productM = require('../models/product');

module.exports = {
    //点击购物车按钮进入购物车
    index: function (req, res) {
        var uid = req.AV.user.id;
        //console.log(uid);
        res.render('cart/index', {title: '购物车'});
    },
    //直接购买进入购物车进行处理后直接跳转到订单生成页面
    singlebuy: function (req, res) {
        var uid = req.AV.user.id;

        var pass_flag = 1;                          // 正常通过标识
        var str = '';                          // 正常通过标识
        var goods = [];                           // 订单商品
        var timestamp = new Date().getTime();

        async.waterfall([
            //删除无效数据
            //function(callback) {
            //    cartM.setProductCheck(uid).then(function(result){
            //        callback(null);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});//code:9999 系统错误
            //    });
            //},
            //查询到购物车价格
            function(callback) {
                cartM.getGoodsPrice(uid).then(function (result) {
                    var goodsPrice =result.GoodsPrice-result.WaiMaiPrice;
                    callback(null,goodsPrice,result.mold);
                });
            },
            //进行满送活动计算
            function(goodsPrice,mold,callback) {

                console.log('==================mold:');
                console.log(mold);
                if(mold == '4'){
                    //res.redirect('/order/confirmOrder/0');
                    callback(null);
                }else{
                    cartM.getActivityRuleMS(goodsPrice,uid).then(function (result) {
                        //res.redirect('/order/confirmOrder/0');
                        callback(null);
                    }).catch(function(err){
                        //res.redirect('/order/confirmOrder/0');
                        callback(null);
                    });
                }
            },
            //通过userid获取用户订单的商品
            function(callback){
                cartM.getProductList(uid,true).then(function(result){
                    var psid;
                    var cid;
                    var specArray;
                    var imgArray;
                    if (result.rows > 0) {
                        for (x in result.data) {
                            psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                            cid = result.data[x].get('product').get('cid');
                            specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                            imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                            goods.push(
                                {
                                    pid:        result.data[x].get('pid'),
                                    pname:      result.data[x].get('product').get('name'),
                                    sid:        result.data[x].get('psid'),
                                    cid:        cid,
                                    sname:      specArray[psid]['name'],
                                    price:      parseFloat(specArray[psid]['grprice']),
                                    size:       parseInt(result.data[x].get('number')),
                                    img:        imgArray[0],
                                    point:      specArray[psid]['point'],
                                    pointRate:  specArray[psid]['pointRate'],
                                    isPoint:    specArray[psid]['isPoint'],
                                    isDiscount: specArray[psid]['isDiscount']
                                }
                            )

                            //如果商品库存　<= 0　或者　　商品库存 <= 购买数量　则中断送流程
                            if(specArray[psid]['inventory'] <= 0 || specArray[psid]['inventory'] < parseInt(result.data[x].get('number'))){
                                pass_flag = 0;
                                str = str + result.data[x].get('product').get('name')+"库存不足;还能购买"+specArray[psid]['inventory']+"份;";
                            }
                        }
                        if(pass_flag == 0){
                            callback({code:509, msg:str});
                        }else{
                            callback(null);
                        }
                    }else{
                        callback({code:510, msg:'购物车内无商品'});
                    }
                });
            },
            //生成一个临时订单
            function(callback){
                console.log('<===========生成一个临时订单===========>');

                var data = {};

                data['orderid'] = 'O'+timestamp;
                data['goods'] = goods;
                data['uid']=uid;
                data['status']=1;
                data['canceltime']=timestamp+(2*60);
                orderM.addTempOrder(data).then(function(result){
                    //保存成功
                    callback(null);
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新商品库存
            function(callback){
                for (var x in goods) {
                    productM.updateInventory(goods[x].pid,goods[x].sid,-goods[x].size).then(function(result){
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
                callback(null,timestamp);
            }
        ],function(err,result){

            if(err){
                console.log("err");
                console.log(err);
                res.json(err);
            }
            console.log("result");
            console.log(result);
            res.json(result);
        });
    },
    //1.清理购物车无效数据
    setProductCheckAjax:function(req, res){
        var uid = req.AV.user.id;
        async.waterfall([
            //判断购物车内是否有商品id为916和917的商品
            function(cb){
                serviceM.findTuiJianProduct('tjsp_cart').then(function(data){
                    cb(null, data);
                }).catch(function(err){
                    cb(null, []);
                })
            },
            function(products,cb){
                if(products.length<1){
                    cb(null);
                }else{
                    console.log(products);
                    //var products = [{pid:705,psid:2496,number:1},{pid:749,psid:2304,number:1}] ;
                    async.eachSeries(products,function(pro,cb1){
                        var pid = pro.id,
                            psid = pro.psid,
                            number = pro.number || 1 ;
                        cartM.insertProToCartBySys(pid,psid,number,uid).then(function(data){
                            //console.log('加入成功')
                            cb1(null)
                        }).catch(function(err){
                            cb1(null)
                        })
                    },function(){
                        cb(null)
                    })
                }
            },
            function(cb){
                cartM.setProductCheck(uid).then(function(result){
                    //console.log('清理成功')
                    var jsonresult = {code: result.code, msg:result.msg};
                    cb(null, jsonresult)
                    //res.json(jsonresult);
                }).catch(function(err){
                    var jsonresult = {code: err.code, msg:err.msg};
                    cb(null, jsonresult)
                    //res.json(jsonresult);
                });
            }
        ],function(err,results){
            if(err){
                res.json(err)
            }else{
                res.json(results)
            }
        });
    },
    //2.获取显示购物车被选中商品货物总价格
    getGoodsPriceAjax:function(req, res){
        var uid = req.AV.user.id;
        cartM.getGoodsPrice(uid).then(function (result) {
            var jsonresult = {code: result.code, msg:result.msg, GoodsPrice: result.GoodsPrice,WaiMaiPrice:result.WaiMaiPrice};
            res.json(jsonresult);
        }).catch(function(err){
            var jsonresult = {code: err.code, msg:err.msg};
            res.json(jsonresult);
        });

    },
    ////购物车AJAX数据请求与angular通信
    //3获取满减规则列表
    getActivityRuleMJAjax: function (req, res) {
        var GoodsPrice = req.query.GoodsPrice;
        var ruleArray = new Array();
        /***模拟数据***/
        /* ruleArray.push(
         {objectId:'axaa22222sas',name:'全场消费满70减10元',checked:false}
         );*/
        //获取真实数据
        cartM.getActivityRuleMJ(GoodsPrice).then(function (result) {
            for (x in result.ruleList) {
                ruleArray.push({
                    objectId: result.ruleList[x].id,
                    name: result.ruleList[x].get('name'),
                    checked: result.ruleList[x].get('checked')
                });
            }
            var RuleMJresult = {code: result.code, discountPrice: result.discountPrice, ruleArray: ruleArray};
            res.json(RuleMJresult);
        }).catch(function(err){
            var RuleMSresult = {code: err.code, msg: err.reason};
            res.json(RuleMSresult);
        });;
    },
    //4获取满送规则列表
    getActivityRuleMSAjax:function(req,res){
        var GoodsPrice = req.query.GoodsPrice;
        var ruleArray = new Array();
        var uid = req.AV.user.id;
      /*  /!***模拟数据***!/
         ruleArray.push(
         {objectId:'axaa22222sas',name:'全场消费满70减送西瓜',checked:true}
         );*/
        //获取真实数据
        cartM.getActivityRuleMS(GoodsPrice,uid).then(function (result) {
                for (x in result.ruleList) {
                    ruleArray.push({
                        objectId: result.ruleList[x].id,
                        name: result.ruleList[x].get('name'),
                        title: result.ruleList[x].get('title'),
                        checked: result.ruleList[x].get('checked')
                    });
                }

                var RuleMSresult = {code: result.code, msg: "ok", ruleArray: ruleArray};
                res.json(RuleMSresult);

        }).catch(function(err){
            var RuleMSresult = {code: err.code, msg: err.reason};
            res.json(RuleMSresult);
        });

    },
    //5获取购物车商品数据列表
    getProductListAjax: function (req, res) {
        var uid = req.AV.user.id;
        var ProductArray = new Array();
        /***模拟数据***/
        /*ProductArray.push(
         {objectId:'ac2q221010012sdsd',name:'越南红心火龙果越南红心火龙果',specname:'3斤',img:'http://7xj380.com1.z0.glb.clouddn.com/2015-07-09_559e1d865ce39.jpg?imageView2/1/w/200/h/200/q/100',number:1,price:8.6,mold:0,checked:true,uid:"ccccseww"},
         {objectId:'ac2q221010012sdsd',name:'越南红心火龙果越南红心火龙果',specname:'3斤',img:'http://7xj380.com1.z0.glb.clouddn.com/2015-07-09_559e1d865ce39.jpg?imageView2/1/w/200/h/200/q/100',number:10,price:8.6,mold:0,checked:false,uid:"ccccseww"},
         {objectId:'ac2q221010012sdsd',name:'越南红心火龙果越南红心火龙果',specname:'3斤',img:'http://7xj380.com1.z0.glb.clouddn.com/2015-07-09_559e1d865ce39.jpg?imageView2/1/w/200/h/200/q/100',number:1,price:8.6,mold:1,checked:true,uid:"ccccseww"},
         {objectId:'ac2q221010012sdsd',name:'越南红心火龙果越南红心火龙果',specname:'3斤',img:'http://7xj380.com1.z0.glb.clouddn.com/2015-07-09_559e1d865ce39.jpg?imageView2/1/w/200/h/200/q/100',number:1,price:8.6,mold:2,checked:true,uid:"ccccseww"}
         )*/
        //获取真实数据
        cartM.getProductList(uid).then(function (result) {
            console.log("================================begin");
            var psid;
            var specArray;
            var imgArray;
           // console.log('控制器！！！！！！！');
           // console.log(result);
            if (result.rows > 0) {
                for (x in result.data) {

                    psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                    specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                    imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组

                    ProductArray.push(
                        {
                            //返回到前端的购物车商品数据
                            objectId: result.data[x].id,
                            pid:result.data[x].get('pid'),
                            cid:result.data[x].get('product').get('cid'),
                            name: result.data[x].get('product').get('name'),
                            specname: specArray[psid]['name'],
                            inventory:specArray[psid]['inventory'],
                            img: imgArray[0],
                            number: result.data[x].get('number'),
                            inputnumber: result.data[x].get('number'),
                            price: specArray[psid]['grprice'],
                            mold: result.data[x].get('mold'),
                            checked: result.data[x].get('checked'),
                            uid: result.data[x].get('uid')
                        }
                    )
                }
            }
            console.log("================================end");
            var jsonresult = {code: result.code, rows: result.rows, ProductArray: ProductArray};
            res.json(jsonresult);
        });


    },
    getProList: function (req, res) {
        //var uid = '55ebf5a760b2b52c4de9536a';
        var uid = req.AV.user.id;
        var obj = new Array();

        cartM.getProductList(uid,true).then(function(result){
            var psid;
            var specArray;
            var imgArray;
            if (result.rows > 0) {
                for (x in result.data) {

                    psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                    specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                    imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                    obj.push(
                        {
                            objectId: result.data[x].id,
                            pid:result.data[x].get('pid'),
                            name: result.data[x].get('product').get('name'),
                            specname: specArray[psid]['name'],
                            inventory:specArray[psid]['inventory'],
                            img: imgArray[0],
                            number: result.data[x].get('number'),
                            price: specArray[psid]['grprice'],
                            mold: result.data[x].get('mold'),
                            uid: result.data[x].get('uid')
                        }
                    )
                }
            }
            res.json(obj);
        }).catch(function(err){
            res.error(err);
        });


    },
    //购物车商品选中切换
    setProductCheckedAjax:function(req, res){
        var objectid=req.query.CartProductId;
        var checked =req.query.Checked;
        if(checked=='true'){checked=true;}else{checked=false;}
        cartM.setProductChecked(objectid,checked).then(function(result){
            var jsonresult = {code: result.code, msg:result.msg};
            res.json(jsonresult);
        });
    },
    //删除购物车中的商品
    delCartProductAjax:function(req,res){
        var objectid=req.query.CartProductId;
        if(objectid){
            cartM.delCartProduct(objectid).then(function(result){
                var jsonresult = {code: result.code, msg:result.msg};
                res.json(jsonresult);
            }).catch(function(err){
                var jsonresult = {code: err.code, msg:err.reason};
                res.json(jsonresult);
            });
        }else{
            res.end('objectid is null');
        }
    },
    //修改购物车商品数量
    setProductQuantityAjax:function(req,res){
        var objectid=req.query.CartProductId;
        var oldNum=parseInt(req.query.NumberOld);
        var newNum=parseInt(req.query.NumberNew);

        if(objectid){

            cartM.setProductQuantity(objectid,oldNum,newNum).then(function(result){
                var jsonresult = {code: result.code, msg:result.msg};
                res.json(jsonresult);
            }).catch(function(err){
                var jsonresult = {code: err.code, msg:err.msg};
                res.json(jsonresult);
            });
        }else{
            res.end('objectid is null');
        }
    },
    //设置全选按钮操作
    setProductCheckedAllAjax:function(req,res){
        var uid = req.AV.user.id;
        var checked =req.query.Checked;
        if(checked=='true'){checked=true;}else{checked=false;}
        cartM.setProductCheckedAll(uid,checked).then(function(result){
            var jsonresult = {code: result.code, msg:result.msg};
            res.json(jsonresult);
        }).catch(function(err){
            var jsonresult = {code: err.code, msg:err.msg};
            res.json(jsonresult);
        });
    }

}